<?php
namespace app\common\model\orderhawa;

use app\api\controller\mytool\Sendmessage;
use app\api\controller\Pub;
use app\api\controller\sync\Synccreate;
use app\common\model\buss\Buss;
use app\common\model\coll\Collection;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\common\model\cost\Costtype;
use app\common\model\orderdata\Goods;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\power\Rolepower;
use app\common\model\quotation\QuotationList;
use app\common\model\transit\Transitcompany;
use app\common\model\transit\TransitUser;
use app\common\model\user\User;
use think\Model;
use app\common\model\revenue_ap\Raplist;

class HawaList extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'hawaorderlist';
    protected $pk    = 'HawaListId';

    const STATEINT       = 0; //创建状态
    const STATEWAIT      = 1; //等待接单
    const STATEWAITOK    = 2; //已接单
    const STATETRANSPORT = 3; //运输中
    const STATEOK        = 4; //已完成
    const STATEDELETE    = 404; //被删除的订单
    const CONFRIMHAWA    = 1;
    const CONFRIMBUSS    = 10;
    const CONFRIMOK      = 11;
    const STATEARRAY     = [['待下单', '已下单'], ['待分配', '已分配'], ['待接单', '已接单'], ['待核实', '运输中'], ['待入库', '已入库']];
    const ORDERNUMBERPER = 'H';
    public function companyinfo()
    {
        return $this->hasOne('app\common\model\company\Company', 'CompanyId', 'CompanyId');
    }
    public function receiptinfo()
    {
        return $this->hasOne('app\common\model\orderreceipt\ReceiptList', 'ReceiptListId', 'ReceiptListId');
    }
    public function bussinfo()
    {
        return $this->hasOne('app\common\model\buss\Buss', 'UserId', 'BussinessId');
    }
    public function userbussinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'BussinessId');
    }
    public function listinfo()
    {
        return $this->hasMany('app\common\model\orderhawa\Hawa', 'HawaListId', 'HawaListId');
    }
    public function tranuserinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'TransitUserId');
    }

    public function collection()
    {
        return $this->hasMany(Collection::class, 'CompanyId', 'CompanyId');
    }
    /**
     * 状态分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1 => '全部订单', 0 => '待分配', 1 => '待接单', 2 => '待核实', 3 => '运输中', 4 => '已入库'];
        if ($value !== '') {
            if ($value == HawaList::STATEDELETE) {
                return '已删除';
            } else {
                return $status[$value];
            }
        }
        return $status;
    }

    /**
     * 获取订单列表
     * @param  [type] $data    [主数据]
     * @param  string $type    [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data, $type = 'hawa', $is_page = true)
    {

        $rdata    = HawaList::where('State', '<>', HawaList::STATEDELETE);
        $userinfo = User::getinfo();

        if ($type == 'hawa') {
            $company = Company::where('UserId', $userinfo->UserId)->find();
            $rdata   = $rdata->where('CompanyId', $company->CompanyId);
            $rdata   = $rdata->with(['bussinfo', 'listinfo']);
            $visible = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'bussinfo.UserName', 'bussinfo.CardNumber', 'bussinfo.CarNumber', 'bussinfo.UserTel', 'bussinfo.UserImg', 'bussinfo.CarImg'];
        } else if ($type == 'buss') {
            $rdata   = $rdata->where('BussinessId', $userinfo->UserId);
            $rdata   = $rdata->with(['companyinfo', 'listinfo']);
            $visible = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand'];
            if (BUSSSHOWHAWAQUOT) {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight', 'Price', 'FloatingNote'];
            } else {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
            }
        } else if ($type == 'tran') {
            $rdata               = $rdata->where('TransitUserId', Pub::userid());
            $rdata               = $rdata->with(['companyinfo', 'listinfo']);
            $visible             = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel'];
            $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
        } else if ($type == 'tranmana') {
            $transit = Transitcompany::user_getinfo();
            if (empty($transit)) {
                return moerr('没有找到关联的运输单位');
            }
            $rdata               = $rdata->where('TransitCompanyId', $transit->TransitCompanyId);
            $rdata               = $rdata->with(['companyinfo', 'listinfo', 'tranuserinfo']);
            $visible             = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'tranuserinfo.UserId', 'tranuserinfo.Name', 'tranuserinfo.Iphone', 'TransitUserId', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand'];
            $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
        } else if ($type == 'acco') {
            $rdata   = $rdata->with(['bussinfo', 'companyinfo', 'listinfo']);
            $visible = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'SettlementTime', 'TotalCost', 'bussinfo.UserName', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand'];
            if (BUSSSHOWHAWAQUOT) {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight', 'Price', 'FloatingNote'];
            } else {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
            }
        } else if ($type == 'mana') {
            $rdata   = $rdata->with(['bussinfo', 'companyinfo', 'listinfo', 'tranuserinfo']);
            $visible = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'bussinfo.UserName', 'bussinfo.Iphone', 'tranuserinfo.UserId', 'tranuserinfo.Name', 'tranuserinfo.Iphone', 'TotalCost', 'BussinessId', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand'];
            if (BUSSSHOWHAWAQUOT) {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight', 'Price', 'FloatingNote'];
            } else {
                $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
            }
        } else if ($type == 'regulatory') {
//监管单位
            $rdata               = $rdata->with(['bussinfo', 'companyinfo', 'listinfo']);
            $visible             = ['HawaListId', 'State', 'UpTime', 'OrderNumber', 'ConfirmState', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'bussinfo.UserName', 'bussinfo.Iphone', 'BussinessId', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand', 'OrderPassword'];
            $visible['listinfo'] = ['GoodId', 'GoodName', 'HawaId', 'Weight', 'ReceiveWeight'];
        }

        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];

        $rdata = $rdata->select();
        $rdata = $rdata->visible($visible);

        $ndata['list'] = $rdata->toArray();

        $goodid             = get_array_id($ndata, 'GoodId', 'list', 'listinfo');
        $ndata['goodinfo']  = Goods::getlist($goodid);
        $ndata['statetext'] = HawaList::getStatusText();
        if ($type == 'tran') {
            $ndata['statemenu'] = $ndata['statetext'];
            unset($ndata['statemenu'][0]);
            unset($ndata['statemenu'][4]);
        }
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }

    /**
     * 获取订单列表
     * @return [type] [description]
     */
    public static function Managetlist($data, $state = -1)
    {
        if ($state == -1) {
            $rdata = HawaList::where('State', '<>', HawaList::STATEDELETE);
        } else {
            $rdata = HawaList::where('State', $state);
        }
        $option = come_model_option($data, $rdata);
        $rdata  = $option['rdata'];
        $data   = $option['data'];
        $rdata  = $rdata->with(['bussinfo', 'companyinfo', 'listinfo']);

        $rdata = $rdata->select();
        $rdata->visible(['HawaListId', 'State', 'UpTime', 'OrderNumber', 'companyinfo.Name', 'companyinfo.CompanyId', 'companyinfo.Lat', 'companyinfo.Lon', 'companyinfo.Tel', 'bussinfo.UserName', 'LoadingTime', 'SettlementTime', 'TotalCost', 'TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitEscortId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitUser', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand']);

        $ndata['list']      = $rdata->toArray();
        $goodid             = get_array_id($ndata, 'GoodId', 'list', 'listinfo');
        $ndata['goodinfo']  = Goods::getlist($goodid);
        $ndata['statetext'] = HawaList::getStatusText();
        $ndata['pageinfo']  = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        return $ndata;
    }

    /**
     * 判断列表中的产品状态是否可操作
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id, $hidden = [], $hidloag = true)
    {
        $data = HawaList::where('State', '<>', HawaList::STATEDELETE)->where('HawaListId', $id)->find();
        if (empty($data)) {
            return moerr('没有找到您需要的订单');
        } else {
            if ($hidloag) {
                $hidden = array_merge(['OperationLog'], $hidden);
                $data   = $data->hidden($hidden)->toArray();
            } elseif (empty($hidden)) {
                $data = $data->toArray();
            } else {
                $data = $data->hidden($hidden)->toArray();
            }
            return sok($data);
        }
    }
    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id, $type = 'hawa')
    {
        if ($type == 'buss' || $type == 'hawa') {
            $data = self::liststate($id, ['SettlementImg', 'SettlementNote', 'SettlementTime', 'FloatingNote']);
        } elseif ($type == 'mana') {
            $data = self::liststate($id, [], false);
        } elseif ($type == 'print') {
            $data = self::liststate($id, ['UpImg', 'UpNote', 'UpImg', 'UpTime', 'LoadingNote', 'DistributionTime', 'DistributionUserId', 'DistributionNote', 'QuotationListId', 'QuotationCost', 'FloatingCost', 'TotalCost', 'FloatingNote', 'SettlementImg', 'SettlementNote', 'SettlementTime']);
        } else {
            $data = self::liststate($id);
        }
        if (!$data['code']) {return $data;}
        $rdata              = $data['msg'];
        $rdata['GoodsList'] = Hawa::getlist($rdata, $type);
        if ($type == 'buss') {
            if ($rdata['BussinessId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            //业务员是否有查看订单费用的权利
            if (!BUSSSHOWHAWAQUOT) {
                unset($rdata['QuotationCost']);
                unset($rdata['FloatingCost']);
                unset($rdata['TotalCost']);
                // unset($rdata['QuotationListId']);
            } else {
                $rdata['quot'] = QuotationList::getinfo();
            }

            $rdata['companyinfo'] = Company::user_getinfo($rdata['CompanyId']);
            // $rdata['hawa'] = User::getpublicinfo($rdata['UpUserId']);
        } else if ($type == 'acco') {
            if(!empty($rdata['RAPListId'])){
               $sb = Raplist::getinfo($rdata['RAPListId'],'mana',false);
               if($sb['code']){ $rdata['rap'] = $sb['msg'];}
            }

            $rdata['companyinfo'] = Company::user_getinfo($rdata['CompanyId']);
            // $rdata['hawa'] = User::getpublicinfo($rdata['UpUserId']);
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
            $rdata['coll'] = Collection::get_company_info($rdata['CompanyId']);
            $rdata['cost'] = Costtype::getcostlist($id, 'orderhawa');
        } else if ($type == 'hawa') {
            if (empty($rdata['UpUserId'])) {
                $sb = Company::get($rdata['CompanyId']);
                if ($sb['UserId'] !== Pub::userid()) {
                    return moerr('没有权限');
                }
            } else if ($rdata['UpUserId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            //确认订单前无法查看转移联单
            if ($rdata['State'] !== HawaList::STATEOK) {
                $rdata['OrderPassword'] = '';
            }
            //收款账户
            $rdata['Account'] = Collection::where('CompanyId', Collection::SELFCOMPANYID)->where('State', Collection::STATEOK)->find();
            $rdata['buss']    = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
        } else if ($type == 'mana') {
            $rdata['companyinfo'] = Company::user_getinfo($rdata['CompanyId']);
            // $rdata['hawa'] = User::getpublicinfo($rdata['UpUserId']);
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
            $rdata['coll'] = Collection::get_company_info($rdata['CompanyId']);
            if (Rolepower::ispower(203008)) {
                $rdata['cost'] = Costtype::getcostlist($id, 'orderhawa');
            }
        } else if ($type == 'tran') {
            if (!BUSSSHOWHAWAQUOT) {
                unset($rdata['FloatingCost']);
                unset($rdata['TotalCost']);
                unset($rdata['QuotationCost']);
                // unset($rdata['QuotationListId']);
            }
            //运维单位收集员是否能查看并操作价格
            if (!TRAN_OPERATION_HAWA_PRICE) {
                unset($rdata['ContractId']); //删除合同id
                unset($rdata['FloatingCost']);
                unset($rdata['TotalCost']);
                unset($rdata['QuotationCost']);
            }

            $tm = Transitcompany::user_getinfo();
            if (empty($tm) && $rdata['TransitUserId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            $rdata['TRAN_OPERATION_HAWA_PRICE'] = TRAN_OPERATION_HAWA_PRICE;
            $rdata['companyinfo']               = Company::user_getinfo($rdata['CompanyId']);
            $rdata['buss']                      = (empty($rdata['BussinessId']) ? [] : Buss::user_getinfo($rdata['BussinessId']));
        } else if ($type == 'print') {
            $rdata['companyinfo'] = Company::user_getinfo($rdata['CompanyId'], '', [], ['Name', 'Tel', 'Address', 'UserTel', 'UserName', 'UpUserId']);
            if (empty($rdata['UpUserId'])) {
                $rdata['companyuser'] = [
                    'Name'   => $rdata['companyinfo']['UserName'],
                    'Iphone' => $rdata['companyinfo']['UserTel'],
                ];
            } else {
                $rdata['companyuser'] = User::getpublicinfo($rdata['UpUserId']);
            }
            $rdata['mycompany'] = ['Name' => COMPANYALLNAME, 'Address' => COMPANYADDRESS, 'NumberCard' => COMPANYNUMBERCARD];
            if (empty($rdata['ReceiptListId'])) {
                $rdata['receipt'] = [
                    'Name'          => '',
                    'Iphone'        => '',
                    'WarehouseTime' => '',
                ];
            } else {
                $sb                                = ReceiptList::get($rdata['ReceiptListId']);
                $rdata['receipt']                  = User::getpublicinfo($sb['WarehouseId']);
                $rdata['receipt']['WarehouseTime'] = $sb['WarehouseTime'];
            }
        } else {
            return moerr('参数错误');
        }
        if (!empty($rdata['TransitUserId'])) {
            $rdata['TransitUser'] = User::getpublicinfo($rdata['TransitUserId']);
        }
        if (!empty($rdata['ContractId'])) {
            $rdata['Contractlist'] = Contract::ordergetbindcontractlist($rdata['ContractId']);
        }
        $rdata['TRANSITESCORT'] = TRANSITESCORT;
        $rdata['StateList']     = HawaList::STATEARRAY;
        return ['code' => true, 'msg' => $rdata];

    }

    /**
     * 新增方法
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function screate($idata, $type = 'hawa')
    {
        $userinfo = User::getinfo();
        if ($type == 'hawa') {
            //判断是否连续触发
            $sb = HawaList::where('UpUserId', $userinfo->UserId)->where('UpTime', '>', date('Y-m-d H:i', time() - 60))->find();
            if (!empty($sb)) {
                return moerr('在一分钟内您已下单，请于一分钟后尝试提交。');
            }
            $companyinfo = Company::user_getinfo();
            //基础信息
            $data['State'] = HawaList::STATEINT;
            //设置用户已确认订单
            $data['ConfirmState'] = HawaList::CONFRIMHAWA;
            //产废人信息
            $data['CompanyId'] = $companyinfo->CompanyId;
            $data['UpUserId']  = $userinfo->UserId;
        } else if ($type == 'buss') {
            $companyinfo = Company::user_getinfo($idata['id']);
            //基础信息
            if (empty($idata['State'])) {
                $data['State'] = HawaList::STATEWAITOK;
            } else {
                if ($idata['State'] !== '2' && $idata['State'] !== '3') {
                    return moerr('订单状态选择错误');
                } else {
                    $data['State'] = $idata['State'];
                }
            }
            $data['ArriveTime']  = $idata['ArriveTime'];
            $data['BussinessId'] = Pub::userid();
            //设置收集员已确认订单
            if (empty($companyinfo['UserId'])) {
                $data['ConfirmState'] = HawaList::CONFRIMOK;
            } else {
                $data['ConfirmState'] = HawaList::CONFRIMBUSS;
            }
            //产废人信息
            $data['UpUserId'] = $companyinfo->UserId;
            //运输单位信息
            $filed = ['TransitCompanyId', 'TransitCompanyName', 'TransitCompanyAddress', 'TransitNumber', 'TransitTel', 'TranSportId', 'TranSportType', 'TransitBrandNumber', 'TransitDriverId', 'TransitDrvierName', 'TransitDrvierTel', 'TransitEscortId', 'TransitEscortName', 'TransitEscortTel', 'TransitUserId', 'TransitEndPoint', 'TransitStartTime', 'TransitStartingPoint', 'TransitViaLand', 'ReceiptAddress', 'ReceiptName', 'ReceiptNumberCard'];
            foreach ($filed as $key => $value) {
                if (!empty($idata[$value])) {
                    $data[$value] = $idata[$value];
                }
            }

            //收集单位信息 收集单位地址
            if (!empty($idata['ReceiptAddress'])) {
                $data['ReceiptAddress'] = $idata['ReceiptAddress'];
            }else{
                 $data['ReceiptAddress'] = COMPANYADDRESS;
            }

            //收集单位信息 收集单位名称
            if (!empty($idata['ReceiptName'])) {
                $data['ReceiptName'] = $idata['ReceiptName'];
            }else{
                $data['ReceiptName'] = COMPANYALLNAME;
            }

            //收集单位 证件号
            if (!empty($idata['ReceiptNumberCard'])) {
                $data['ReceiptNumberCard'] = $idata['ReceiptNumberCard'];
            }else{
                $data['ReceiptNumberCard'] = COMPANYNUMBERCARD;
            }
            


            //若选择为后续上门 则判断是否存在运输公司的id，若存在则将状态修改为待接单
            if (!empty($idata['TransitCompanyId']) && $idata['State'] == '2') {
                $data['State'] = HawaList::STATEWAIT;
            }
            //合同信息
            $idata['CompanyId'] = $companyinfo->CompanyId; //将公司id 复制到此以供合同抵扣时检测
            if (!empty($idata['ContractId'])) {
                $data['ContractId']             = $idata['ContractId'];
                $data['Cont_DisposalFee']       = $idata['Cont_DisposalFee'];
                $data['Cont_UniversalDisposal'] = $idata['Cont_UniversalDisposal'];
                $data['Cont_SurplusShipNum']    = $idata['Cont_SurplusShipNum'];
                //抵扣额度
                Contract::deduct($idata);
            }

        }

        $data['OrderNumber']   = HawaList::ORDERNUMBERPER . date('YmdH') . $userinfo->UserId . rand(10, 99);
        $data['CompanyId']     = $companyinfo->CompanyId;
        $data['OrderPassword'] = md5($data['CompanyId'] . $data['OrderNumber'] . $data['CompanyId']) . date('His', time()) . rand(10, 99);
        $data['UpNote']        = $idata['UpNote'];
        $data['UpImg']         = $idata['UpImg'];
        $data['UpTime']        = date('Y-m-d H:i', time());
        //报价信息
        if (HAWAQUOT == 'acco') {
            //会计报价模式
            $data['QuotationListId'] = $idata['quot']['QuotationListId'];
            $data['QuotationCost']   = $idata['quot']['QuotationCost'];
            $data['FloatingCost']    = $idata['quot']['FloatingCost'];
            $data['TotalCost']       = $idata['quot']['TotalCost'];
        } else if (HAWAQUOT == 'buss') {
            //业务员报价模式
            $data['QuotationListId'] = -1;
            $data['FloatingCost']    = 0;
            if (($type == 'buss') && (!empty($idata['QuotationCost']))) {
                $data['QuotationCost'] = $idata['QuotationCost'];
                $data['TotalCost']     = $idata['QuotationCost'];
            } else {
                $data['QuotationCost'] = 0;
                $data['TotalCost']     = 0;
            }
            $idata['quot']['pricelist'] = -1;
        }
        //保存主表
        $hawalist   = HawaList::create($data);
        $HawaListId = $hawalist->HawaListId;
        if ($type == 'hawa') {
            //保存子表
            $hawa = Hawa::screate($HawaListId, $idata['goodlist'], $idata['valuelist'], $idata['quot']['pricelist'], $idata);
        } else {
            //保存子表
            $hawa = Hawa::screate($HawaListId, $idata['goodlist'], $idata['valuelist'], $idata['quot']['pricelist'], $idata);
        }
        //判断子表是否保存成功
        if (!$hawa['code']) {
            $hawalist->delete();
            return serr($hawa['msg']);
        }
        return sok($hawalist);
    }
    /**
     * 删除订单
     * @return [type] [description]
     */
    public static function deleteorderlist($id)
    {
        $data = HawaList::get($id);
        if (empty($data)) {
            return moerr('没有找到您的订单');
        }
        // if ($data['State'] >= HawaList::STATETRANSPORT) {
        //     return moerr('订单已进入运输状态无法删除');
        // }
        if ($data['State'] == HawaList::STATEOK) {
            return moerr('订单已完成入库，无法删除');
        }
        $ndata['id']    = $id;
        $ndata['State'] = HawaList::STATEDELETE;
        HawaList::user_reinfo($ndata);
        return sok('订单已删除');
    }
    /**
     * 判断订单数组状态是否完全一致
     * @param  [type] $data  [description]
     * @param  [type] $state [description]
     * @return [type]        [description]
     */
    public static function test_state($data, $state)
    {
        $sb = HawaList::where('HawaListId', 'in', $data)->where('State', $state)->count();
        if ($sb == count($data)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 订单分配
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function dist($data)
    {
        $userinfo = User::getinfo();
        if (!empty($data['ids'])) {
            $sb = HawaList::where('HawaListId', 'in', $data['ids']);
        } else if (!empty($data['id'])) {
            $sb = HawaList::where('HawaListId', $data['id']);
        } else {
            return moerr('分配参数错误');
        }

        switch ((int) $data['groupid']) {
            case 1:
                $count = $sb->update(['DistributionTime' => date('Y-m-d H:i', time()),
                    'DistributionUserId'                     => $userinfo->UserId,
                    // 'BussinessId'                            => $data['bussid'],
                    'State'                                  => HawaList::STATEWAIT]);
                break;
            case 2:
                //  分配给运输单位管理员
                $tc    = Transitcompany::get($data['bussid']);
                $count = $sb->update(['DistributionTime' => date('Y-m-d H:i', time()),
                    // 'BussinessId'                            => Pub::userid(),
                    'DistributionUserId'                     => $userinfo->UserId,
                    'TransitCompanyId'                       => $data['bussid'],
                    'TransitCompanyName'                     => $tc['Name'],
                    'TransitNumber'                          => $tc['TransitNumber'],
                    'TransitTel'                             => $tc['Tel'],
                    'TransitCompanyAddress'                  => $tc['Address'],
                    'State'                                  => HawaList::STATEWAIT]);
                break;
            case 3:
                //分配给运输单位指定的收集员
                $tcom  = TransitUser::get($data['bussid']);
                $tc    = Transitcompany::get($tcom->TransitCompanyId);
                $count = $sb->update(['DistributionTime' => date('Y-m-d H:i', time()),
                    // 'BussinessId'                            => Pub::userid(),
                    'DistributionUserId'                     => $userinfo->UserId,
                    'TransitCompanyId'                       => $tcom->TransitCompanyId,
                    'TransitUserId'                          => $tcom->UserId,
                    'TransitCompanyName'                     => $tc['Name'],
                    'TransitNumber'                          => $tc['TransitNumber'],
                    'TransitTel'                             => $tc['Tel'],
                    'TransitCompanyAddress'                  => $tc['Address'],
                    'State'                                  => HawaList::STATEWAIT]);
                break;

            default:
                return moerr('订单分配出错');
                break;
        }

        if (empty($count)) {
            return moerr('没有找到需要分配的订单');
        }
        return sok('成功分配' . $count . '个订单');
    }

    /**
     * 修改收集员
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changedist($data)
    {
        $userinfo = User::getinfo();
        if (!empty($data['id']) && !empty($data['bussid'])) {
            $sb = HawaList::where('HawaListId', $data['id'])->find();
        } else {
            return moerr('分配参数错误');
        }
        if ($sb->State >= 3) {
            return moerr('订单已在运输中无法修改收集员');
        }
        $sb->save(['DistributionTime' => date('Y-m-d H:i', time()),
            'DistributionUserId'          => $userinfo->UserId,
            'BussinessId'                 => $data['bussid'],
            'State'                       => 1]);
        return sok('修改成功');
    }

    /**
     * 修改运输单位
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changetran($data)
    {
        $userinfo = User::getinfo();
        if (!empty($data['id']) && !empty($data['tid'])) {
            $sb = HawaList::where('HawaListId', $data['id'])->find();
        } else {
            return moerr('分配参数错误');
        }
        if ($sb->State >= 3) {
            return moerr('订单已在运输中无法修改运输单位');
        }
        if (empty($data['tid'])) {
            return moerr('缺少运输单位');
        }
        $tdata = Transitcompany::get($data['tid']);
        if (empty($tdata)) {
            return moerr('没有找到此运输单位');
        }
        if ($sb->TransitCompanyId !== $data['tid']) {
            $sb->TransitUserId         = null;
            $sb->TransitCompanyId      = $data['tid'];
            $sb->TransitCompanyName    = $tdata['Name'];
            $sb->TransitCompanyAddress = $tdata['Address'];
            $sb->TransitNumber         = $tdata['TransitNumber'];
            $sb->TransitTel            = $tdata['Tel'];
            $sb->TranTransitDrvierName = null;
            $sb->TranSportId           = null;
            $sb->TransitDriverId       = null;
            $sb->TransitEscortId       = null;
            $sb->TranSportType         = null;
            $sb->TransitBrandNumber    = null;
            $sb->TransitDrvierName     = null;
            $sb->TransitDrvierTel      = null;
        }

        if (!empty($data['uid'])) {
            $sb->TransitUserId = $data['uid'];
        }

        $sb->DistributionTime   = date('Y-m-d H:i', time());
        $sb->DistributionUserId = $userinfo->UserId;
        $sb->State              = 1;
        $sb->save();
        return sok('修改成功');
    }

    /**
     * 修改收集员
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function changestate($iddata)
    {
        $userinfo = User::getinfo();
        if (!empty($data['id']) && !empty($data['bussid'])) {
            $sb = HawaList::where('HawaListId', $data['id'])->find();
        } else {
            return moerr('分配参数错误');
        }
        if ($sb->State >= 3) {
            return moerr('订单已在运输中无法修改收集员');
        }
        $sb->save(['DistributionTime' => date('Y-m-d H:i', time()),
            'DistributionUserId'          => $userinfo->UserId,
            'BussinessId'                 => $data['bussid'],
            'State'                       => 1]);
        return sok('修改成功');
    }

    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param  boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = HawaList::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if ($key == 'State' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $info->getStatusText((int) $value);
                $ovalue  = $info->getStatusText((int) $ovalue);
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if (!empty($value) && $ovalue !== $value) {
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            return moerr('没有找到需要调整的数据');
        }
    }

    public static function getfiledname($str)
    {
        $filename = ['UpNote' => '下单备注', 'UpImg'                => '下单附带图片',
            'QuotationCost'       => '报价费用', 'FloatingCost'         => '浮差金额', 'TotalCost'                => '合计金额',
            'FloatingNote'        => '浮差备注', 'SettlementImg'        => '结算凭证',
            'SettlementTime'      => '结算时间', 'SettlementNote'       => '结算备注', 'State'                    => '订单状态',
            'TransitCompanyId'    => '运输单位id', 'TransitCompanyName' => '运输单位名字', 'TransitCompanyAddress'  => '运输单位地址',
            'TransitNumber'       => '运输证号', 'TransitTel'           => '运输单位联系电话', 'TranSportId'          => '运输工具id',
            'TranSportType'       => '运输工具类型', 'TransitBrandNumber' => '运输工具牌号', 'TransitDriverId'        => '运输驾驶员id',
            'TransitDrvierName'   => '运输驾驶员名称', 'TransitDrvierTel'  => '运输驾驶员电话', 'TransitUserId'         => '运输收集员id',
            'TransitEndPoint'     => '运输终点', 'TransitStartTime'     => '运输实际起运时间', 'TransitStartingPoint' => '运输起始点',
            'TransitViaLand'      => '运输经由地', 'TransitEscortId'     => '运输押运员id', 'ReceiptAddress'        => '收集单位地址',
            'ReceiptName'         => '收集单位名称', 'ReceiptNumberCard'  => '收集单位证号','RAPListId'=>'挂账id'
        ];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

    public static function getgoodinfo($bussid, $state, $type = 'buss')
    {
        if ($type == 'buss') {
            $idarr = HawaList::where('State', $state)->where('BussinessId', $bussid);
        } else if ($type == 'transport') {
            $idarr      = HawaList::where('State', $state)->where('TranSportId', $bussid);
            $companlist = $idarr->with('companyinfo')->select()->visible(['HawaListId', 'companyinfo.Name', 'TransitUserId', 'BussinessId'])->toArray();
            $orderlist  = [];
            foreach ($companlist as $key => $value) {
                $orderlist[$value['HawaListId']] = $value;
            }
        } else if ($type == 'retransport') {
            $idarr      = HawaList::where('ReceiptListId', $bussid);
            $companlist = $idarr->with('companyinfo')->select()->visible(['HawaListId', 'companyinfo.Name', 'TransitUserId', 'BussinessId'])->toArray();
            $orderlist  = [];
            foreach ($companlist as $key => $value) {
                $orderlist[$value['HawaListId']] = $value;
            }
        }

        $idarr = $idarr->column('HawaListId');
        if ($type == 'buss') {
            $data = Hawa::where('HawaListId', 'in', $idarr)->group('GoodId')->with('good_info')->field('GoodId,sum(Weight) as Weight')->select();
        } else if ($type == 'transport') {
            //整合每个子订单显示企业名称
            $data     = Hawa::where('HawaListId', 'in', $idarr)->order('GoodId desc')->select();
            $goodid   = get_array_id($data, 'GoodId');
            $goodinfo = Goods::getlist($goodid);
            $goods    = [];
            foreach ($goodinfo as $key => $value) {
                $goods[$value['GoodId']] = $value;
            }
            $nlist                   = [];
            $sb                      = 0;
            $nlist[$sb]['good_info'] = $goods[$data[$sb]['GoodId']];
            $nlist[$sb]['Weight']    = 0;
            $nlist[$sb]['list']      = [];
            foreach ($data as $key => $value) {
                $value['info'] = $orderlist[$value['HawaListId']];
                if ($nlist[$sb]['good_info']['GoodId'] == $value['GoodId']) {
                    $nlist[$sb]['list'][] = $value;
                    $nlist[$sb]['Weight'] = $value['Weight'] + $nlist[$sb]['Weight'];
                } else {
                    $sb                      = $sb + 1;
                    $nlist[$sb]['good_info'] = $goods[$value['GoodId']];
                    $nlist[$sb]['Weight']    = $value['Weight'];
                    $nlist[$sb]['list'][]    = $value;
                }
            }
            $data = $nlist;
        } else if ($type == 'retransport') {
            //整合每个子订单显示企业名称
            $data     = Hawa::where('HawaListId', 'in', $idarr)->order('GoodId desc')->select();
            $goodid   = get_array_id($data, 'GoodId');
            $goodinfo = Goods::getlist($goodid);
            $goods    = [];
            foreach ($goodinfo as $key => $value) {
                $goods[$value['GoodId']] = $value;
            }
            $nlist = [];
            $sb    = 0;
            if (empty($data)) {
                return moerr('数据错误：产废子订单为空');
            }
            $nlist[$sb]['good_info'] = $goods[$data[$sb]['GoodId']];
            $nlist[$sb]['Weight']    = 0;
            $nlist[$sb]['list']      = [];
            foreach ($data as $key => $value) {
                $value['info'] = $orderlist[$value['HawaListId']];
                if ($nlist[$sb]['good_info']['GoodId'] == $value['GoodId']) {
                    $nlist[$sb]['list'][] = $value;
                    $nlist[$sb]['Weight'] = $value['Weight'] + $nlist[$sb]['Weight'];
                } else {
                    $sb                      = $sb + 1;
                    $nlist[$sb]['good_info'] = $goods[$value['GoodId']];
                    $nlist[$sb]['Weight']    = $value['Weight'];
                    $nlist[$sb]['list'][]    = $value;
                }
            }
            $data = $nlist;
        }
        return $data;
    }
    /**
     * 货物入库登记
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function receipt($data)
    {
        //检测勾选的订单状态
        if (!HawaList::test_state($data['HawaListIds'], HawaList::STATETRANSPORT)) {
            return sok('勾选的订单状态无法直接入库');
        }
        //标记入库订单id
        HawaList::where('HawaListId', 'in', $data['HawaListIds'])->update(['ReceiptListId' => $data['id'], 'State' => HawaList::STATEOK]);
        foreach ($data['HawaListIds'] as $key => $value) {
            //通知入库
            Sendmessage::Orderhawa(5, $value);
            //同步中心操作
            Synccreate::hawaorder($value);
        }
        return sok();
    }

    /**
     * 获取统计数据
     * @return [type] [description]
     */
    public static function getsummary($date = '', $enddate = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d', time());
        } else {
            $date = date('Y-m-d', strtotime($date));
        }
        if (empty($enddate)) {
            $sb               = HawaList::where('LoadingTime', '>', $date)->where('LoadingTime', '<=', $date . ' 24:00')->field('TotalCost,HawaListId')->select();
            $rdata['timestr'] = mb_substr($date, 8, 2) . '号';
        } else {
            $enddate = date('Y-m-d', strtotime($enddate));
            $sb      = HawaList::where('LoadingTime', '>', $date)->where('LoadingTime', '<=', $enddate . ' 24:00')->field('TotalCost,HawaListId')->select();
            if (mb_substr($date, 5, 2) !== mb_substr($enddate, 5, 2)) {
                $rdata['timestr'] = mb_substr($date, 5, 5) . '~' . mb_substr($enddate, 6, 5);
            } else {
                $rdata['timestr'] = mb_substr($date, 8, 2) . '~' . mb_substr($enddate, 8, 2);
            }
        }
        if (empty($sb)) {
            return [];
        }

        if (empty($enddate)) {
            $rdata['wait'] = HawaList::where('LoadingTime', '>', $date)->where('LoadingTime', '<=', $date . ' 24:00')->whereNull('SettlementTime')->count();
        } else {
            $rdata['wait'] = HawaList::where('LoadingTime', '>', $date)->where('LoadingTime', '<=', $enddate . ' 24:00')->where('SettlementTime', 'EXP', 'IS NULL')->count();
        }

        $HawaListIds = get_array_id($sb, 'HawaListId');
        //货物重量
        $rdata['goodlist'] = Hawa::where('HawaListId', 'in', $HawaListIds)->group('GoodId')->with('goodInfo')->field('GoodId,sum(Weight) as Weight')->select();
        $rdata['Weight']   = 0;
        foreach ($rdata['goodlist'] as $key => $value) {
            $rdata['Weight'] = $value['Weight'] + $rdata['Weight'];
        }

        if ($rdata['Weight'] > 1000) {
            $rdata['Weight']     = $rdata['Weight'] / 1000;
            $rdata['WeightUnit'] = '吨';
        } else {
            $rdata['WeightUnit'] = '公斤';
        }
        $rdata['Price'] = 0;
        foreach ($sb as $key => $value) {
            $rdata['Price'] = $value['TotalCost'] + $rdata['Price'];
        }
        if ($rdata['Price'] > 1000) {
            $rdata['Price']     = $rdata['Price'] / 10000;
            $rdata['PriceUnit'] = '万元';
        } else {
            $rdata['PriceUnit'] = '元';
        }
        return $rdata;
    }

    /**
     * 同步中心关联指令
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function sync_relation_ssysb($id)
    {
        $data        = HawaList::get($id);
        $receiptlist = ReceiptList::get($data['ReceiptListId']);
        $company     = Company::get($data['CompanyId']);
        if (!empty($data['BussinessId'])) {
            $buss = User::get($data['BussinessId']);
        }
        if (!empty($data['TransitUserId'])) {
            $tarnuser = User::get($data['TransitUserId']);
        }

        $rdata[] = ['name' => '下单时间', 'text' => $data['UpTime']];
        $rdata[] = ['name' => '入库时间', 'text' => $receiptlist['WarehouseTime']];
        $rdata[] = ['name' => '产废单位', 'text' => $company['Name']];
        if (!empty($buss)) {
            $rdata[] = ['name' => '业务员', 'text' => $buss['Name']];
        }
        $rdata[] = ['name' => '运输单位', 'text' => $data['TransitCompanyName']];
        if (!empty($tranuser)) {
            $rdata[] = ['name' => '运输单位收集员', 'text' => $tranuser['Name']];
        }
        $rdata[] = ['name' => '运输牌号', 'text' => $data['TransitBrandNumber']];
        return $rdata;
    }

}
